package com.jinlejia.erp.ui.house;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.freedom.yefeng.yfrecyclerview.YfLoadMoreListener;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.DistrictAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.ActivityInterestDistrictBinding;
import com.jinlejia.erp.ui.common.CommonDeleteDialog;
import com.jinlejia.erp.utils.DataFilter;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 兴趣小区
 */
public class InterestDistrictActivity extends AppCompatActivity implements YfLoadMoreListener {

    private String csCode;
    DistrictAdapter adapter;
    private int page = 1;
    private boolean mLoadingLock = false;

    private ActivityInterestDistrictBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_interest_district);
        binding.btBack.setOnClickListener(this::onClick);
        binding.btAdd.setOnClickListener(this::onClick);

        csCode = getIntent().getStringExtra("csCode");

        binding.yfRecycler.setHasFixedSize(true);
        binding.yfRecycler.setLayoutManager(new LinearLayoutManager(this));
        ArrayList<Map<String, Object>> list = new ArrayList();
        adapter = new DistrictAdapter(list);
        binding.yfRecycler.setAdapter(adapter);

        adapter.setOnDeleteListiner((i, name) -> {
            CommonDeleteDialog dialog = new CommonDeleteDialog(InterestDistrictActivity.this, "删除", "确定删除" + name + "?");
            dialog.show();
            dialog.setConfirmListener(() -> remove(i, name));
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }

    private void getData() {
        String url;
        if (getIntent().getStringExtra("type").equals("sale") || getIntent().getStringExtra("type").equals("shs")) {
            url = ApiConfig.ENJOY_SHS_ESTATE_LIST;
        } else {
            url = ApiConfig.ENJOY_RENT_ESTATE_LIST;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pageSize", 20);
        jsonObject.put("pageIndex", page);
        jsonObject.put("csCode", csCode);
        OkHttpUtils.postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(InterestDistrictActivity.this, response, adapter)) {
                            JSONArray data = JSON.parseArray(response.get("data").toString());
                            //数据列表
                            ArrayList<Map<String, Object>> list = JSON.parseObject(data.toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            if (page == 1) {
                                adapter.setData(list);
                            } else {
                                adapter.addData(list);
                            }
                        } else if (response.get("code").toString().equals("303")) {
                            //没有更多
                            page--;
                        }
                        mLoadingLock = false;
                    }
                });
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_back:
                finish();
                break;
            case R.id.bt_add:
                //添加意向小区
                Intent intent = new Intent(this, AddDistrictActivity.class);
                intent.putExtra("csCode", csCode);
                intent.putExtra("type", getIntent().getStringExtra("type"));
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    private void remove(final int p, String name) {
        String url;
        if (getIntent().getStringExtra("type").equals("shs")|| getIntent().getStringExtra("type").equals("sale")) {
            url = ApiConfig.REMOVE_SHS_ENJOY_ESTATE;
        } else {
            url = ApiConfig.REMOVE_RENT_ENJOY_ESTATE;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("estateName", name);
        jsonObject.put("csCode", csCode);
        OkHttpUtils.postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(InterestDistrictActivity.this, response)) {
                            adapter.notifyItemRemoved(p);
                            adapter.mData.remove(p);
                            adapter.notifyItemRangeChanged(p, adapter.mData.size() - p);
                            if (adapter.mData.size() == 0)
                                adapter.changeMode(YfListMode.MODE_EMPTY);
                        }
                    }
                });
    }

    @Override
    public void loadMore() {
        if (adapter.getData().size() % 20 == 0) {
            if (mLoadingLock) {
                return;
            }
            mLoadingLock = true;
            page++;
            adapter.addFooter("loading");

            getData();
        }else if( adapter.getData().size() > 10 ){
            adapter.addFooter(R.string.is_all);
        }
    }
}
